package com.weetop.akly.activity.mine;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectChangeListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.classic.adapter.BaseAdapterHelper;
import com.classic.adapter.CommonRecyclerAdapter;
import com.weetop.akly.R;
import com.weetop.akly.activity.communicationIndex.UserDetailActivity;
import com.weetop.akly.appConfig.GlobalConstants;
import com.weetop.akly.base.BaseActivity;
import com.weetop.akly.base.mvp.BaseModel;
import com.weetop.akly.base.mvp.BaseObserver;
import com.weetop.akly.base.mvp.BasePresenter;
import com.weetop.akly.bean.MemberBean;
import com.weetop.akly.bean.SalaryBean;
import com.weetop.akly.utils.BaseUtils;
import com.weetop.akly.utils.GlideUtil;
import com.weetop.akly.utils.widget.MaxRecyclerView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SalaryActivity extends BaseActivity {

    @BindView(R.id.tv_month)
    TextView tvMonth;
    @BindView(R.id.tv_department)
    TextView tvDepartment;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_account)
    TextView tvAccount;
    @BindView(R.id.rv_data)
    MaxRecyclerView rvData;
    @BindView(R.id.tv_real_salary)
    TextView tvRealSalary;
    @BindView(R.id.tv_should_salary)
    TextView tvShouldSalary;
    @BindView(R.id.rv_debit)
    RecyclerView rvDebit;
    @BindView(R.id.tv_pay_salary)
    TextView tvPaySalary;
    @BindView(R.id.rv_pay)
    MaxRecyclerView rvPay;
    private TimePickerView pvDate;

    private CommonRecyclerAdapter<SalaryBean.DataBean> dataAdapter, debitAdapter, payAdapter;
    private ArrayList<SalaryBean.DataBean> data = new ArrayList<>();
    private ArrayList<SalaryBean.DataBean> debit = new ArrayList<>();
    private ArrayList<SalaryBean.DataBean> pay = new ArrayList<>();

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_salary);
        ButterKnife.bind(this);
        setTitleInfo("我的工资条");
        String monthDate = getTime(new Date());
        String monthText = getMonthText(new Date());
        tvMonth.setText(monthText);
        getSalary(monthDate);
        initDatePicker();
        initDataList();
        initPayList();
        initDebitList();
    }

    private void initDataList() {
        dataAdapter = createAdapter(data);
        GridLayoutManager layout = new GridLayoutManager(this, 2) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        rvData.setLayoutManager(layout);
        rvData.setAdapter(dataAdapter);
    }

    private void initPayList() {
        if (payAdapter == null) {
            payAdapter = createAdapter(pay);
        }
        GridLayoutManager layout = new GridLayoutManager(this, 2) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        rvPay.setLayoutManager(layout);
        rvPay.setAdapter(payAdapter);
    }

    private void initDebitList() {
        debitAdapter = createAdapter(debit);
        GridLayoutManager layout = new GridLayoutManager(this, 2) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        rvDebit.setLayoutManager(layout);
        rvDebit.setAdapter(debitAdapter);
    }

    private CommonRecyclerAdapter<SalaryBean.DataBean> createAdapter(ArrayList<SalaryBean.DataBean> list) {
        CommonRecyclerAdapter<SalaryBean.DataBean> adapter = new CommonRecyclerAdapter<SalaryBean.DataBean>(mContext, R.layout.item_salary, list) {
            @Override
            public void onUpdate(BaseAdapterHelper helper, SalaryBean.DataBean item, int position) {
                helper.setText(R.id.tv_salary_title, item.getTitle());
                helper.setText(R.id.tv_salary_value, item.getValue());
                if (position % 2 == 0) {
                    helper.setVisible(R.id.v_line, View.GONE);
                }
                if (list.size() % 2 != 0 && list.size() > 3) {
                    if (position == list.size() - 2 || position == list.size() - 3) {
                        helper.setVisible(R.id.hb_line, View.VISIBLE);
                    }
                    if (position == list.size() - 1) {
                        helper.setVisible(R.id.h_line, View.INVISIBLE);
                        helper.setVisible(R.id.vr_line, View.VISIBLE);
                    }
                }
            }
        };
        return adapter;
    }


    private void initDatePicker() {//Dialog 模式下，在底部弹出
        pvDate = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                String monthDate = getTime(date);
                String monthText = getMonthText(date);
                tvMonth.setText(monthText);
                getSalary(monthDate);
                Log.i("pvTime", "onTimeSelect");

            }
        })
                .setTimeSelectChangeListener(new OnTimeSelectChangeListener() {
                    @Override
                    public void onTimeSelectChanged(Date date) {
                        Log.i("pvTime", "onTimeSelectChanged");
                    }
                })
                .setType(new boolean[]{true, true, false, false, false, false})
                .setLabel("年", "月", "", "", "", "")
                .isDialog(true) //默认设置false ，内部实现将DecorView 作为它的父控件。
                .addOnCancelClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Log.i("pvTime", "onCancelClickListener");
                    }
                })
                .setItemVisibleCount(5) //若设置偶数，实际值会加1（比如设置6，则最大可见条目为7）
                .setLineSpacingMultiplier(2.0f)
                .isAlphaGradient(true)
                .build();

        Dialog mDialog = pvDate.getDialog();
        if (mDialog != null) {

            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM);

            params.leftMargin = 0;
            params.rightMargin = 0;
            pvDate.getDialogContainerLayout().setLayoutParams(params);

            Window dialogWindow = mDialog.getWindow();
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim);//修改动画样式
                dialogWindow.setGravity(Gravity.BOTTOM);//改成Bottom,底部显示
                dialogWindow.setDimAmount(0.3f);
            }
        }
    }


    private void getSalary(String month) {
        addDisposable(apiServer.getSalary(month), new BaseObserver<BaseModel<SalaryBean>>(this) {
            @Override
            public void onSuccess(BaseModel<SalaryBean> o) {
                showData(o.getData());
            }

            @Override
            public void onError(String msg) {
                showError(msg);
                showDialog(msg);
            }
        });
    }

    private void showData(SalaryBean salaryBean) {
        SalaryBean.AllBean allBean = salaryBean.getAll();
        SalaryBean.DebitBean debitBean = salaryBean.getDebit();
        SalaryBean.PayBean payBean = salaryBean.getPay();
        SalaryBean.AllBean.UserBean userBean = allBean.getUser();
        tvName.setText(userBean.getName());
        tvAccount.setText(userBean.getCode());
        tvDepartment.setText(userBean.getDepartment());
        tvRealSalary.setText(allBean.getReal());
        tvShouldSalary.setText(debitBean.getReal());
        tvPaySalary.setText(payBean.getReal());
        //data
        data.clear();
        data.addAll(allBean.getData());
        dataAdapter.replaceAll(data);
        //应发
        pay.clear();
        pay.addAll(payBean.getData());
        payAdapter.replaceAll(pay);


        //应扣
        debit.clear();
        debit.addAll(debitBean.getData());
        debitAdapter.replaceAll(debit);
    }

    private String getMonthText(Date date) {
        String pattern = "yyyy年MM月";
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        return format.format(date);
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        Log.d("getTime()", "choice date millis: " + date.getTime());
        String pattern = "yyyy-MM";
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        return format.format(date);
    }

    @OnClick(R.id.tv_month)
    public void onViewClicked(View view) {
        pvDate.show(view);
    }
}
